<template>
	<view class="wrap area-b">
		<u-navbar :title="name||'查看文件'"></u-navbar>
		<view class="file-wrap">
			<view class="file-icon" :style="{backgroundColor:fileIcon.bgColor,color:fileIcon.color}">
				<text class="iconfont" :class="fileIcon.icon"></text>
			</view>
			<view class="file-name u-line-2">
				<text class="u-font-36">{{name}}</text>
			</view>
			<view v-if="localPath" class="btn bg-blue" @tap="openFile">
				<text>打开</text>
			</view>
			<view v-if="!localPath&&!task" class="btn bg-blue" @tap="download">
				<text>下载({{size|fileSize}})</text>
			</view>
			<view v-if="task" class="u-m-t-80">
				<text class="u-font-22 text-gray">文件下载中...({{curSize|fileSize}}/{{totalSize|fileSize}})</text>
			</view>
			<view v-if="task" class="progress">
				<view class="bar bg-gray">
					<view class="inner-bar bg-green" :style="{width: `${progress}%`}">
						
					</view>
				</view>
				<view class="close iconfont icon-failfill text-red" @tap="cancelDL">
					
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	
	
	
	import { 
		downloadFile
	 } from '@/utils/file.js';
	import { toast } from '@/utils/util';
	import { BASE_URL ,Bucket ,Region } from '@/utils/constant';
	import { getBaseUrl} from "@/utils/config.js"
	const DIR = '_doc/media/'
	export default {
		data() {
			return {
				url:'',
				name:'',
				size:0,
				localPath:'',
				task:null, 
				progress:0, 
				curSize:0, 
				totalSize:0, 
			};
		},
		computed:{
			fileIcon(){
				const name = this.name
				if(/\.{1}(rar|zip|arjz|lzh|jar)$/i.test(name)){
					return {
						bgColor:'#92999d',
						color:'#FFFFFF',
						icon:'icon-file-archive'
					} 
				}
				if(/\.{1}(mp3|aac|wav|wma|cda|flac|m4a|mid|mka|mp2|mpa|mpc|ape|ofr|ogg|ra|wv|tta|ac3|dts)$/i.test(name)){
					return {
						bgColor:'#409af7',
						color:'#FFFFFF',
						icon:'icon-file-audio'
					} 
				}
				if(/\.{1}(xls|xlsx|xlsm|et)$/i.test(name)){
					return {
						bgColor:'#56ab7d',
						color:'#FFFFFF',
						icon:'icon-file-excel'
					}
				}
				if(/\.{1}(jpg|jpeg|png|gif)$/i.test(name)){
					return {
						bgColor:'#409af7',
						color:'#FFFFFF',
						icon:'icon-file-image'
					}
				}
				if(/\.{1}(pdf)$/i.test(name)){
					return {
						bgColor:'#e85d58',
						color:'#FFFFFF',
						icon:'icon-file-pdf'
					}
				}
				if(/\.{1}(ppt|pptx)$/i.test(name)){
					return {
						bgColor:'#e87a4e',
						color:'#FFFFFF',
						icon:'icon-file-powerpoint'
					}
				}
				if(/\.{1}(mp4|rmvb|avi|wmv|flv|mkv|webm|mov)$/i.test(name)){
					return {
						bgColor:'#409af7',
						color:'#FFFFFF',
						icon:'icon-file-video'
					}
				}
				if(/\.{1}(doc|docx)$/i.test(name)){
					return {
						bgColor:'#355795',
						color:'#FFFFFF',
						icon:'icon-file-word'
					}
				}
				return {
						bgColor:'#AAAAAA',
						color:'#FFFFFF',
						icon:'icon-filefill'
				}
			}
		},
		filters:{
			fileSize(val){
				if(isNaN(val)){
					return ''
				}
				if(val>1024*1024*1024*1024){
					return `${(val/(1024*1024*1024*1024)).toFixed(1)} TB`
				}else if(val>1024*1024*1024){
					return `${(val/(1024*1024*1024)).toFixed(1)} GB`
				}else if(val>1024*1024){
					return `${(val/(1024*1024)).toFixed(1)} MB`
				}else if(val>1024){
					return `${(val/1024).toFixed(1)} KB`
				}else{
					return `${val} B`
				}
			}
		},
		onLoad({url,name,size=0}) {
			this.url = url
			this.name = name
			this.size = Number(size)
		},
		methods:{
			async download(){
				// #ifdef H5
				const link = document.createElement("a");
				if(this.url.includes(Bucket)&&this.url.includes(Region)){
					link.href = this.url
				}else{
					link.href = `${getBaseUrl()}/common/download/${this.url.replace(/^http(s?):\/\/.*\/profile\//i,'')}?name=${this.name}`;
				}
				link.download = this.name;
				link.click();
				// #endif
				// #ifdef APP-PLUS
				try{
					const tempPath = await new Promise((resolve,reject)=>{
						const task = uni.downloadFile({
							url:this.url,
							success({tempFilePath,statusCode}) {
								console.log(statusCode)
								if(statusCode==200){
									resolve(tempFilePath)
								}else{
									reject(new Error('下载失败'))
								}
							},
							fail:reject,
							complete:()=>{
								this.clearTask()
							}
						})	
						task.onProgressUpdate(({progress,totalBytesWritten,totalBytesExpectedToWrite})=>{
							this.progress = progress
							this.totalSize = totalBytesExpectedToWrite
							this.curSize = totalBytesWritten
						})
						this.task = task
					})
					const fileEntry = await new Promise((resolve,reject)=>{
						plus.io.resolveLocalFileSystemURL( tempPath, resolve, reject );
					})
					const dirEntry = await new Promise((resolve,reject)=>{
						plus.io.resolveLocalFileSystemURL( DIR, resolve, (e)=>{
							plus.io.requestFileSystem( plus.io.PRIVATE_DOC,({root})=>{
								root.getDirectory('media/',{create:true},resolve)
							});
						});
					}) 
					await new Promise((resolve,reject)=>{
						plus.io.resolveLocalFileSystemURL( DIR+this.name, (entry)=>{
							entry.remove(resolve,reject)
						},resolve);
					})
					const targetEntry = await new Promise((resolve,reject)=>{
						fileEntry.copyTo(dirEntry,this.name,resolve,reject)
					})
					this.localPath = targetEntry.toLocalURL()
				}catch(e){
					console.log(e)
					if(e.errMsg=='downloadFile:fail abort'){
						return
					}
					toast(e.message)
				}
				// #endif
			},
			clearTask(){
				this.task = null
				this.totalSize = 0
				this.curSize = 0
				this.progress = 0
			},
			cancelDL(){ 
				this.task&&this.task.abort()
				this.clearTask()
			},
			openFile(){
				// #ifdef H5
				window.open(this.localPath)
				// #endif
				// #ifdef APP-PLUS
				plus.runtime.openFile(this.localPath)
				// #endif
			}
		}
	}
</script>

<style>
page{
	background-color: #FAFAFA;
}
</style>
<style lang="scss" scoped>
	.file-wrap{
		margin-top: 200rpx;
		padding: 0 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		.file-icon{
			width: 150rpx;
			height: 150rpx;
			border-radius: 20rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 90rpx;
		}
		.file-name{
			margin-top: 20rpx;
			text-align: center;
		}
		.btn{
			margin-top: 30rpx;
			padding: 20rpx 30rpx;
			border-radius: 10rpx;
		}
		.progress{
			display: flex;
			align-items: center;
			width: 100%;
			.bar{
				flex: 1;
				height: 10rpx;
				border-radius: 10rpx;
				overflow: hidden;
			}
			.inner-bar{
				width: 50%;
				height: 10rpx;
			}
			.close{
				font-size: 50rpx;
				margin-left: 20rpx;
			}
		}
	}
</style>
